package com.eight.cloud.mybatisplus.datasource;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Set;

/**
 * @ClassName: DataSourceManager
 * @Author: TXC
 * @Date: 2025-06-17 16:39
 **/
@Slf4j
@AutoConfiguration
@ConditionalOnProperty(prefix = "dynamics.datasource", name = "enable", havingValue = "true")
public class DataSourceManager {
    @Resource
    private DataSource dataSource;
    @Resource
    private DataSourceCreator dataSourceCreator;

    /**
     * 添加数据源
     * @param dataSourceProperty 数据源配置信息
     */
    public Set<String> addDataSource(DataSourceProperty dataSourceProperty) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource creatorDataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        ds.addDataSource(dataSourceProperty.getPoolName(), creatorDataSource);
        return ds.getDataSources().keySet();
    }

    /**
     * 删除数据源
     * @param poolName 数据源名称
     */
    public void removeDataSource(String poolName) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(poolName);
    }

    /**
     * 获取所有数据源
     */
    public Set<String> getDataSources() {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        return ds.getDataSources().keySet();
    }

    /**
     * 切换数据源
     * @param poolName 数据源名称
     */
    public void switchDataSource(String poolName) {
        // 清空当前线程的数据源信息
        DynamicDataSourceContextHolder.clear();
        // 切换到对应poolName的数据源
        DynamicDataSourceContextHolder.push(poolName);
    }

    public Set<String>  updateDataSource(DataSourceProperty dataSourceProperty) {
        removeDataSource(dataSourceProperty.getPoolName());
        return addDataSource(dataSourceProperty);
    }
}
